<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="库房名称" prop="srName">
        <el-input v-model="queryParams.srName" placeholder="请输入库房名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="库房状态" prop="srState">
        <el-select v-model="queryParams.srState" placeholder="请选择库房状态" clearable>
          <el-option v-for="dict in dict.type.eamp_sr_state" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="库房类型" prop="srType">
        <el-select v-model="queryParams.srType" placeholder="请选择库房类型" clearable>
          <el-option v-for="dict in dict.type.eamp_sr_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['eamp:sr_man:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['eamp:sr_man:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['eamp:sr_man:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['eamp:sr_man:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sr_manList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="srId" />
      <el-table-column label="库房名称" align="center" prop="srName" />
      <el-table-column label="库房总规格" align="center" prop="srSpecification" />
      <el-table-column label="库房当前规格" align="center" prop="srCurrentSpecifications" />
      <el-table-column label="库房类型" align="center" prop="srType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.eamp_sr_type" :value="scope.row.srType" />
        </template>
      </el-table-column>
      <el-table-column label="库房状态" align="center" prop="srState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.eamp_sr_state" :value="scope.row.srState" />
        </template>
      </el-table-column>
      <!--      srCreateUser.nickName-->
      <el-table-column label="创建人" align="center" prop="srCreateBy">
        <template slot-scope="scope">
          {{ getUserName(scope.row.srCreateBy).userName }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="srCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.srCreateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewDetails(scope.row)">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['eamp:sr_man:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['eamp:sr_man:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改库房管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="库房名称" prop="srName">
          <el-input v-model="form.srName" placeholder="请输入库房名称" />
        </el-form-item>
        <el-form-item label="总规格" prop="srSpecification">
          <el-input v-model="form.srSpecification" placeholder="请输入库房总规格" />
        </el-form-item>
        <el-form-item label="库房类型" prop="srType">
          <el-select v-model="form.srType" placeholder="请选择库房类型">
            <el-option v-for="dict in dict.type.eamp_sr_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库房附件" prop="srFile">
          <file-upload v-model="form.srFile" />
        </el-form-item>
        <el-form-item label="库房地址" prop="srAddress">
          <el-input v-model="form.srAddress" placeholder="请选择库房地址" />
          <BaiduMap @address-selected="handleAddressSelected"></BaiduMap>
        </el-form-item>
        <el-form-item label="库房备注" prop="srRemark">
          <el-input v-model="form.srRemark" placeholder="请输入库房备注" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看按钮详情 -->
    <el-dialog title="查看详情" :visible.sync="dialogView" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="true">
        <el-form-item label="库房名称" prop="srName">
          <el-input v-model="form.srName" placeholder="请输入库房名称" disabled />
        </el-form-item>
        <el-form-item label="总规格" prop="srSpecification">
          <el-input v-model="form.srSpecification" placeholder="请输入库房总规格" disabled />
        </el-form-item>
        <el-form-item label="库房类型" prop="srType">
          <el-select v-model="form.srType" placeholder="请选择库房类型" disabled>
            <el-option v-for="dict in dict.type.eamp_sr_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库房附件" prop="srFile">
          <template>
            <file-upload v-model="form.srFile" v-if="form.srFile" />
            <div v-else>无文件上传</div>
            <!-- <div>{{ form.srFile ? form.srFile : "无文件上传" }}</div> -->
          </template>
        </el-form-item>
        <el-form-item label="库房地址" prop="srAddress">
          <el-input v-model="form.srAddress" placeholder="请选择库房地址" disabled />
        </el-form-item>
        <el-form-item label="库房备注" prop="srRemark">
          <el-input v-model="form.srRemark" placeholder="请输入库房备注" type="textarea" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Viewcancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSr_man, getSr_man, delSr_man, addSr_man, updateSr_man, srAllList } from "@/api/eamp/sr_man";
import BaiduMap from '@/components/MapSelect/BaiduMap.vue';
import { listUser } from "@/api/system/user";

export default {
  name: "Sr_man",
  dicts: ['eamp_sr_type', 'eamp_sr_state'],
  components: {
    BaiduMap,
  },
  data() {
    return {
      user: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库房管理表格数据
      sr_manList: [],
      userList: [],
      srAllList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        srName: null,
        srSpecification: null,
        srCurrentSpecifications: null,
        srType: null,
        srState: null,
        srFile: null,
        srAddress: null,
        srCreateBy: null,
        srCreateTime: null,
        srUpdateBy: null,
        srUpdateTime: null,
        srRemark: null,
        delFlg: 1
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        srName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        srSpecification: [{ required: true, message: "请输入规格", trigger: "blur" }],
        srType: [{ required: true, message: "请选择类型", trigger: "change" }],
      }
    };
  },

  created() {
    this.getList();
    this.getUserList();
    this.getSrAllList();
  },
  methods: {
    // 获取不分页所有库房列表
    getSrAllList() {
      srAllList().then(res => {
        this.srAllList = res.rows;
      })
    },
    // 获取用户列表
    getUserList() {
      listUser().then(res => {
        this.userList = res.rows;
        // console.log(this.userList);
      })
    },
    getUserName(srCreateBy) {
      const user = this.userList.find(item => item.userId == srCreateBy);
      return user ? user : ''
    },

    handleAddressSelected(address) {
      this.form.srAddress = address; // 更新selectedAddress的值
    },
    /** 查询库房管理列表 */
    getList() {
      this.loading = true;
      listSr_man(this.queryParams).then(response => {
        this.sr_manList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        srId: null,
        srName: null,
        srSpecification: null,
        srCurrentSpecifications: null,
        srType: null,
        srState: null,
        srFile: null,
        srAddress: null,
        srCreateBy: null,
        srCreateTime: null,
        srUpdateBy: null,
        srUpdateTime: null,
        srRemark: null,
        delFlg: 1
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.srId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加库房管理";
    },
    // 查看按钮
    handleViewDetails(row) {
      this.form = row
      this.dialogView = true; // 打开弹窗层
    },
    Viewcancel() {
      this.dialogView = false;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const srId = row.srId || this.ids
      console.log(11111111);
      getSr_man(srId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库房管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.srId != null) {
            updateSr_man(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 在新增操作中加入检查逻辑
            if (this.srAllList.some(item => item.srName == this.form.srName)) {
              // 如果库房名称已存在,给出提示并终止新增操作
              this.$message.error('该库房名称已存在,不可重复添加');
            } else {
              // 如果库房名称不存在,允许新增操作并给出成功提示
              addSr_man(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const srIds = row.srId || this.ids;
      let srCurrentSpecifications = null;
      let srSpecification = null;
      if (Array.isArray(srIds)) {
        for (let index = 0; index < srIds.length; index++) {
          getSr_man(srIds[index]).then(res => {
            srCurrentSpecifications = res.data.srCurrentSpecifications;
            srSpecification = res.data.srSpecification;
            if (srCurrentSpecifications != srSpecification) {
            this.$message.error('当前' + srIds[index] + '库房存在参试设备，禁止删除');
          }
          }); 
          return;
        }
      };
      if (row.srCurrentSpecifications !== row.srSpecification) {
        this.$message.error('当前库房存在参试设备，禁止删除');
        return;
      }
      this.$modal.confirm('是否确认删除库房管理编号为"' + srIds + '"的数据项？').then(function () {
        return delSr_man(srIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('eamp/sr_man/export', {
        ...this.queryParams
      }, `sr_man_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
